//
//  OpenEyesViewController.m
//  Eyeshot
//
//  Created by lanou3g on 15/6/30.
//  Copyright (c) 2015年 lanou3g.com. All rights reserved.
//

#import "OpenEyesViewController.h"
#import "OpenEyesCell.h"
#import "OpenDetailViewController.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "DBTool.h"
@interface OpenEyesViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (strong,nonatomic) UITableView *openEyesTableView;//列表
@property (strong,nonatomic) NSMutableArray *openSouceArray;//模型数组
@property (strong,nonatomic) NSMutableArray *headerSouceArray;//区头模型数组

@property (assign,nonatomic) NSInteger requestNum;//网络请求数据条数

@property (strong,nonatomic) UIScrollView *scrollView;//点击cell显示滚动视图
@end

@implementation OpenEyesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _requestNum = 10;//开始请求10条数据
    [self createOPenEyesTableView];
    //设置添加刷新
    [self setupDownFresh];
    [self setupUpFresh];
}

- (void)setupDownFresh{
    //1.添加下拉刷新
    [_openEyesTableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefrshView)];
    //2.
    [_openEyesTableView.header beginRefreshing];
}

- (void)setupUpFresh{
    //1.添加下拉刷新
    [_openEyesTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefrshView)];
    
}

#pragma mark - 刷新视图的两个方法
- (void)headerRefrshView{
    //TODO: 下拉刷新
    [_openEyesTableView.header endRefreshing];
    //1.获得请求管理者
    AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
    //2.设置参数
    NSMutableDictionary *paramters = [[NSMutableDictionary alloc] init];
    paramters[@"num"] = @10;
    NSDate *date = [NSDate date];
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyyMMdd"];
    NSString *dateStr = [formater stringFromDate:date];
    paramters[@"date"] = [NSString stringWithFormat:@"%@",dateStr];
    paramters[@"vc"] = @71;
    paramters[@"vc"] = @"a0697649a6da0b93b9d5883622e005e123f90ff3";
    paramters[@"v"] = @"1.4.0";
    paramters[@"f"] = @"iphone";
    
    //3.先去数据库里找数据
    NSArray *dataArray = [DBTool dataArrayWithParams:nil];
    _headerSouceArray = [[NSMutableArray alloc] init];
    if (dataArray.count) {
        for (NSDictionary *dic in dataArray) {
            _openSouceArray = [[NSMutableArray alloc] init];
            for (NSDictionary *dic1 in dic[@"videoList"]) {
                OpenEyesModel *model = [[OpenEyesModel alloc] init];
                [model setValuesForKeysWithDictionary:dic1];
                [_openSouceArray addObject:model];
            }
            [_headerSouceArray addObject:_openSouceArray];
        }
        //刷新表视图
        [_openEyesTableView reloadData];
        //接受数据停止刷新
        [_openEyesTableView.header endRefreshing];
    } else {
        //4.数据库没有想要的数据,发出GET请求
        [requestManager GET:@"http://baobab.wandoujia.com/api/v1/feed" parameters:paramters success:^(AFHTTPRequestOperation * operation, NSDictionary  *dic) {
            //把请求到的数据存入数据库
            [DBTool saveArray:dic[@"dailyList"]];
            //表视图的数据
            for (NSDictionary *dic1 in dic[@"dailyList"]) {
                //取列表数据
                _openSouceArray = [[NSMutableArray alloc] init];
                for (NSDictionary *dic2 in dic1[@"videoList"]) {
                    OpenEyesModel *model = [[OpenEyesModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic2];
                    [_openSouceArray addObject:model];
                }
                [_headerSouceArray addObject:_openSouceArray];
            }
            //刷新表视图
            [_openEyesTableView reloadData];
            //接受数据停止刷新
            [_openEyesTableView.header endRefreshing];
        } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
            NSLog(@"---请求数据失败:%@",error);
        }];
    }
}
- (void)footerRefrshView{
    //TODO: 上拉刷新
    //1.获得请求管理者
    AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
    //2.设置参数
    NSMutableDictionary *paramters = [[NSMutableDictionary alloc] init];
    paramters[@"num"] = @(_requestNum += 10);
    NSDate *date = [NSDate date];
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyyMMdd"];
    NSString *dateStr = [formater stringFromDate:date];
    paramters[@"date"] = [NSString stringWithFormat:@"%@",dateStr];
    paramters[@"vc"] = @71;
    paramters[@"vc"] = @"a0697649a6da0b93b9d5883622e005e123f90ff3";
    paramters[@"v"] = @"1.4.0";
    paramters[@"f"] = @"iphone";
    //4.数据库没有想要的数据,发出GET请求
    [requestManager GET:@"http://baobab.wandoujia.com/api/v1/feed" parameters:paramters success:^(AFHTTPRequestOperation * operation, NSDictionary  *dic) {
        //删除数据库原来数据
        [DBTool removeAllData];
        //把请求到的数据存入数据库
        [DBTool saveArray:dic[@"dailyList"]];        
        _headerSouceArray = [[NSMutableArray alloc] init];
        for (NSDictionary *dic1 in dic[@"dailyList"]) {
            //取列表数据
            _openSouceArray = [[NSMutableArray alloc] init];
            NSArray *arr = dic1[@"videoList"];
            for (NSDictionary *dic in arr) {
                OpenEyesModel *model = [[OpenEyesModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_openSouceArray addObject:model];
            }
            [_headerSouceArray addObject:_openSouceArray];
        }
        //刷新表视图
        [_openEyesTableView reloadData];
        //接受数据停止刷新
        [_openEyesTableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        NSLog(@"---请求数据失败:%@",error);
    }];
}


#pragma mark - 创建表视图

- (void)createOPenEyesTableView{
    //1初始化表示图
    _openEyesTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _openEyesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //2.设置代理
    _openEyesTableView.dataSource = self;
    _openEyesTableView.delegate = self;
    //3.注册cell类
    [_openEyesTableView registerClass:[OpenEyesCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_openEyesTableView];
}

#pragma mark - 实现表视图代理协议
//1.分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //返回分区数
    return _headerSouceArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //返回区头高度
    return 30;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //自定义区头Label
    //1.区头显示文字,将时间戳转化为日期
    NSString *s = [NSString stringWithFormat:@"%@",[_headerSouceArray[section][0] date]];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[s doubleValue]/1000];
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"MM.dd"];
    NSString *timeString = [formatter1 stringFromDate:date];
    //2.自定义label
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    headerLabel.font = [UIFont systemFontOfSize:20.0];
    headerLabel.textAlignment = NSTextAlignmentCenter;
    NSString *str = [NSString stringWithFormat:@"-%@-",timeString];
    headerLabel.text = str;
    return headerLabel;
}
//2.每个分区
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //返回分组数
    return 5;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //创建cell
    static NSString *reuseIdentifier = @"cell";
    OpenEyesCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (cell == nil) {
        cell = [[OpenEyesCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    cell.openEyesModel = _headerSouceArray[indexPath.section][indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //返回cell高度
    return kScreenH * 0.3;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //点击cell进入详情
    OpenDetailViewController *OpenDetailVC = [[OpenDetailViewController alloc] init];
    OpenDetailVC.openEyesModel = _headerSouceArray[indexPath.section][indexPath.row];
    OpenDetailVC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:OpenDetailVC animated:YES];
}

@end
